<script setup>
import { ref } from 'vue';
import { useUserStore } from '@/stores/userStore';
import { useRouter } from 'vue-router';

const userStore = useUserStore();
const router = useRouter();

const form = ref({
  userid: '', 
  password: ''
});

const errorMessage = ref('');

const handleLogin = async () => {
  // 添加条件判断
  if (!form.value.userid.trim()) {
    errorMessage.value = '请输入用户名';
    return;
  }
  if (!form.value.password.trim()) {
    errorMessage.value = '请输入密码';
    return;
  }

  try {
    await userStore.loginUser(form.value.userid, form.value.password);
    
    router.push('/');
  } catch (error) {
    errorMessage.value = '登录失败，请检查用户名和密码';
  }
};
</script>

<template>
  <div class="login-container">
    <form @submit.prevent="handleLogin" class="login-form">
      <h2>用户登录</h2>
      <div class="form-group">
        <input v-model="form.userid" placeholder="用户ID" class="form-input" /> <!-- 修改为userid -->
      </div>
      <div class="form-group">
        <input v-model="form.password" type="password" placeholder="密码" class="form-input" />
      </div>
      <button type="submit" class="submit-btn">登录</button>
      <p class="register-link">没有账号？<router-link to="/register">立即注册</router-link></p>
      <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    </form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  background-color: #f8f9fa;
}

.login-form {
  width: 400px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.login-form h2 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #3498db;
  outline: none;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #2980b9;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #7f8c8d;
}

.register-link a {
  color: #3498db;
  text-decoration: none;
}

.error-message {
  color: #e74c3c;
  text-align: center;
  margin-top: 15px;
}
</style>